from rest_framework.viewsets import ModelViewSet
from meiduo_admin.utils import MyNumbPage, upload_image
from goods.models import SKUImage, SKU
from .serializers import SKUImageSerializer
from rest_framework.response import Response


class ImageViewSet(ModelViewSet):
    serializer_class = SKUImageSerializer
    queryset = SKUImage.objects.all()
    pagination_class = MyNumbPage

    def create(self, request, *args, **kwargs):
        # 获取参数
        img = request.data.get('image')
        sku_id = request.data.get('sku')
        img_url = upload_image(img)
        if not img_url:
            return Response
        SKUImage.objects.create(sku_id=sku_id, image=img_url)
        SKU.objects.filter(id=sku_id, default_image_url='').update(default_image_url=img_url)
        return Response(status=201)

    def update(self, request, *args, **kwargs):
        # 获取参数
        img = request.data.get('image')
        sku_id = request.data.get('sku')
        pk = kwargs.get('pk')
        img_url = upload_image(img)
        if not img_url:
            return Response(status=400)
        SKUImage.objects.filter(id=pk).update(image=img_url, sku_id=sku_id)
        return Response(status=201)
